package com.rr.easy;

import com.rr.entity.ListNode;

/**
 * @author RR
 * @date 2022/12/18 13:32
 */

/*
* 链表反转
* */
public class ReverseList {
    public ListNode revertList(ListNode node) {
        ListNode pre = null;
        ListNode next = null;
        while (node != null) {
            // 先记录下个节点
            next = node.next;
            // 当前节点的下个结束指向上个节点
            node.next = pre;
            // 当前节点变为下次循环的上个节点
            pre = node;
            // 更新当前节点为下个结点，进入下次循环
            node = next;
        }
        return pre;
    }

    public static void main(String[] args) {
        ReverseList reverseList = new ReverseList();
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        ListNode listNode = reverseList.revertList(n1);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }

    }
}
